var express = require('express');
var router = express.Router();
const Album = require("./album");
const Photo = require("./photo");

/* GET home page. */
router.get('/', async function(req, res, next) {
  var activeAlbum = await Album.findOne({active:true});
  if (!activeAlbum) {
    activeAlbum = await Album.findOne({albumName:"default"});
    activeAlbum.active = true;
    await activeAlbum.save;
  }
  const activeAlbumName = activeAlbum.albumName;
  var albumList = await Album.find();
  var page = Number(req.query.page) || 1;
  var photoList = await Photo.find({albumName:activeAlbumName})
                  .sort("-createTime")
                  .limit(4)
                  .skip((page-1)*4);
  var allPhotos = await Photo.find({albumName:activeAlbumName});
  const maxPage = Math.ceil(allPhotos.length/4);
  return res.render('index', { albumList, photoList, allPhotos, page, maxPage });
});

router.post('/creatAlbum', async function(req, res, next) {
  const { albumName } = req.body;
  await Album.findOneAndUpdate({active:true}, {active:false});
  var album = new Album({
    albumName,
    createTime:new Date(),
    active:true
  });
  await album.save();
  return res.redirect('/');
});

router.post('/deleteAlbum', async function(req, res, next) {
  const { albumName } = req.body;
  if(albumName === "default"){
    await Album.findOneAndUpdate({albumName:"default"},{active:true});
  }else{
    await Album.findOneAndRemove({ albumName });
    await Photo.remove({ albumName });
    console.log("相册"+albumName+"已删除。");
    var activeAlbum = await Album.findOne({active:true});
    if (!activeAlbum) {
      activeAlbum = await Album.findOneAndUpdate({albumName:"default"},{active:true});
    }
  }
  return res.redirect('/');
});

router.post('/changeAlbum', async function(req, res, next) {
  const { albumName } = req.body;
  await Album.findOneAndUpdate({active:true},{active:false});
  var activeAlbum = await Album.findOneAndUpdate({ albumName },{active:true});
  return res.redirect('/');
});

router.post('/readImage', async function(req, res, next) {
  const { imgSrc } = req.body;
  const activeAlbum = await Album.findOne({active:true});
  const activeAlbumName = activeAlbum.albumName;
  console.log("activeAlbumName=",activeAlbumName);
  var photo = new Photo({
    albumName:activeAlbumName,
    imgSrc,
    createTime:new Date()
  });
  await photo.save();
  return res.redirect('/');
});

router.post('/deleteImage', async function(req, res, next) {
  const { photoId } = req.body;
  await Photo.remove({ _id:photoId });
  console.log("图片已删除。");
  return res.redirect('/');
});


module.exports = router;
